#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


//tcp客户端
#define CPORT  10086
#define SPORT  10010
#define IP     "127.0.0.1"
#define SIZE   100

int main()
{
	int socketID = 0;
	struct sockaddr_in addr;
	int addrLength  = 0;
	char buf[SIZE] = "tcp client is ok";
	
	//创建套接字描述符(协议)	 
	socketID = socket( PF_INET, SOCK_STREAM, 0);
	if ( 0 > socketID )
	{
		perror("socket error");
		return -1;
	}
	printf("client  socket ok\r\n");
	
    //绑定自己的地址(ip+port)
	addrLength = sizeof(addr);
	memset(&addr, 0, addrLength);
	addr.sin_family = PF_INET;
	addr.sin_port = htons(CPORT);
	addr.sin_addr.s_addr = INADDR_ANY;
	if ( 0 > bind(socketID, (struct sockaddr *)&addr, addrLength))
	{
		perror("bind error");
		close(socketID);
		return -1;
	}
	printf("client bind ok\r\n");
	
    //设置对方的地址(ip+port) 
	memset(&addr, 0, addrLength);
	addr.sin_family = PF_INET;
	addr.sin_port = htons(SPORT);
	addr.sin_addr.s_addr = inet_addr(IP);	
    //发送连接请求   
	if ( 0 > connect( socketID, (struct sockaddr *)&addr, addrLength ))
	{
		perror("connect error");
		close(socketID);
		return -1;
	}
	printf("client connect ok\r\n");
	
    //通信 
	if (0 > write(socketID, buf, strlen(buf)))
	{
		perror("write error");		
	}
	else 
	{
		printf("client send msg ok, msg:%s\r\n", buf);
	}
    //关闭套接字描述符  
	close(socketID);
	return 0;
}	